//
//  ChatfileRightcell.swift
//  app_rn_frontend
//
//  Created by wanghui on 2018/6/1.
//  Copyright © 2018年 Facebook. All rights reserved.
//

import UIKit
import Kingfisher
import AudioToolbox

class ChatfileRightcell: ChatBaseCell {
    
    @IBOutlet weak var imgtopConstraint: NSLayoutConstraint!
    @IBOutlet weak var bgtopConstraint: NSLayoutConstraint!
    @IBOutlet weak var avatar: UIImageView!
    @IBOutlet weak var createTimelabel: WHLabel!
    @IBOutlet weak var namelabel: UILabel!
    @IBOutlet weak var fileimgbtn: UIButton!
    @IBOutlet weak var bgimg: UIImageView!
    @IBOutlet weak var activityindicator: UIActivityIndicatorView!
    @IBOutlet weak var sendfailureBtn: UIButton!
    @IBOutlet weak var filenameLabel: UILabel!
    @IBOutlet weak var filesizeLabel: UILabel!
    @IBOutlet weak var holderview: UIView!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        self.selectionStyle = UITableViewCell.SelectionStyle.none
        
        self.holderview.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target:self, action:#selector(tapview))
        self.holderview.addGestureRecognizer(tap)
        
        self.avatar.isUserInteractionEnabled = true
        let tapAvatar = UITapGestureRecognizer.init(target: self, action: #selector(tapSelector))
        self.avatar.addGestureRecognizer(tapAvatar)
        
        self.createTimelabel.paddingLeft = 5
        self.createTimelabel.paddingRight = 5
        self.createTimelabel.layer.cornerRadius = 5
        self.createTimelabel.layer.masksToBounds = true
        self.addLongPress()
    }
    
    
    //长按手势
    @objc func addLongPress() {
        let longPressGes = UILongPressGestureRecognizer(target: self, action: #selector(longPressView(_:)))
        //长按等待时间
        longPressGes.minimumPressDuration = 0.5
        
        //长按时候,手指头可以移动的距离
        longPressGes.allowableMovement = 30
        self.holderview.isUserInteractionEnabled = true
        //        self.bubble.addGestureRecognizer(longPressGes)
        self.holderview.addGestureRecognizer(longPressGes)
    }
    
    @objc func longPressView(_ longPressGest:UILongPressGestureRecognizer) {
        if longPressGest.state == .began {
            //短振动，普通短震，3D Touch 中 Peek 震动反馈
            //            let soundShort = SystemSoundID(1519)
            
            //            //普通短震，3D Touch 中 Pop 震动反馈,home 键的振动
            let soundMiddle = SystemSoundID(1520)
            //
            //            // 连续三次短震
            //            let soundThere = SystemSoundID(1521)
            
            //执行震动
            AudioServicesPlaySystemSound(soundMiddle)
            
            
            
            //长按手势开启
            self.addMenuItem()
        }else {
            
        }
    }
    
    //长按头像实现@功能
    @objc func avatarAddLongPress() {
        let longPressGes = UILongPressGestureRecognizer.init(target: self, action: #selector(avatarLongPress(_:)))
        longPressGes.minimumPressDuration = 0.5
        
        longPressGes.allowableMovement = 30
        self.avatar.isUserInteractionEnabled = true
        self.avatar.addGestureRecognizer(longPressGes)
    }
    
    @objc func avatarLongPress(_ longPressGest:UILongPressGestureRecognizer) {
        if longPressGest.state == UIGestureRecognizer.State.began {
            //长按手势添加@
            self.delegate?.addAtInTextviewDelegate(msg: model)
        }else {
            
        }
    }
    
    func addMenuItem() {
        let zhuanfaItem = UIMenuItem(title: "转发", action: #selector(zhuanfaAction))
        let menuVC = UIMenuController.shared
        menuVC.menuItems = [zhuanfaItem]
        menuVC.showMenu(from: self.holderview, rect: self.holderview.bounds)
    }
    
    
    override var canBecomeFirstResponder: Bool {
        return true
    }
    
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        if action == #selector(zhuanfaAction) {
            return true
        }
        if action == #selector(delete) {
            return true
        }
        return false
    }
    
    @objc override func delete(_ sender: Any?) {
        //删除
        self.delegate?.deleteDelegate(msg:model)
    }
    
    @objc func reportAction() {
        self.delegate?.reportDelegate(msg:model)
    }
    
    
    @objc func zhuanfaAction() {
        self.delegate?.zhuanfaDelegate(msg: model)
    }
    
    
    @objc  func tapview() {
        print("点击了该文件")
        let url = Common.fileUrl(model.storeFile ?? "unknown.unknown")
        let param = Param(fileName: model.fileName ??  "unknown", ext: model.ext ??  "unknown", storeFile: model.storeFile ??  "unknown.unknown",size: model.fileSize ?? 0)
        delegate?.openWebPage(param)
    }
    
    @objc func tapSelector() {
        print("点击了头像")
    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        
        // Configure the view for the selected state
    }
    
    override func setup(model: ChatMessage) {
        super.setup(model: model)
        if let avatar = model.avatar {
            self.avatar.kf.setImage(with: KF.ImageResource(downloadURL: Common.avatarUrl(avatar) ?? URL(string: "localhost")!), placeholder: #imageLiteral(resourceName:"defaultAvatar"),options: [.processor(CryptorProcessor())])
        } else {
            self.avatar.image = #imageLiteral(resourceName:"defaultAvatar")
        }
        self.filenameLabel.text = "\(model.fileName ?? "unknown").\(model.ext ?? "unknown")"
        self.filesizeLabel.text = Common.getSizeString(size: model.fileSize ?? 0)
        if let ext = model.ext {
            if ext == "doc" || ext == "docx" {
                fileimgbtn.setImage(#imageLiteral(resourceName:"wordFile") , for: .normal)
            } else if ext == "xls" || ext == "xlsx" {
                fileimgbtn.setImage(#imageLiteral(resourceName:"excelFile") , for: .normal)
            } else if ext == "pdf" {
                fileimgbtn.setImage(#imageLiteral(resourceName:"pdfFile") , for: .normal)
            } else if ext == "txt" || ext == "text" {
                fileimgbtn.setImage(#imageLiteral(resourceName:"txtFile") , for: .normal)
            } else if ext == "ppt" || ext == "pptx" {
                fileimgbtn.setImage(#imageLiteral(resourceName:"pptFile") , for: .normal)
            } else {
                fileimgbtn.setImage(#imageLiteral(resourceName:"defaultFile") , for: .normal)
            }
        }
        self.createTimelabel.isHidden = !model.showTimeLabel
        self.createTimelabel.text = model.timeStr
        self.namelabel.text = model.fromName
        self.imgtopConstraint.constant = self.createTimelabel.isHidden == true ? 8: 40
        
        //        self.namelabel.isHidden = true
        //        self.bgtopConstraint.constant = cell.namelabel.isHidden == true ? 0 : 18
        if model.status == .pending {
            self.activityindicator.isHidden = false
            self.activityindicator.startAnimating()
        } else {
            self.activityindicator.isHidden = true
            self.activityindicator.stopAnimating()
        }
        self.sendfailureBtn.isHidden = !(model.status == .error)
        if model.chatType == .p2p {
            bgtopConstraint.constant = 0
            namelabel.isHidden = true
        }
    }
    
    override func updateUI() {
        super.updateUI()
        DispatchQueue.main.async {
            if self.model.status == .pending {
                self.activityindicator.isHidden = false
                self.activityindicator.startAnimating()
            } else {
                self.activityindicator.isHidden = true
                self.activityindicator.stopAnimating()
            }
            self.sendfailureBtn.isHidden = !(self.model.status == .error)
        }
    }
    
}
